import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/jiance/comentorder.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:toast/toast.dart';

class GurateedetailPage extends StatefulWidget {
  final String oid;
  GurateedetailPage(this.oid);
  State<StatefulWidget> createState() {
    return new DetailState(this.oid);
  }
}

class DetailState extends State<GurateedetailPage> {
  final String oid;
  DetailState(this.oid);
  List formList;
  Map orderinfo = new Map();
  String price = "0.00"; //dhjahdah
  String status = "订单状态";
  String order_sn = "订单编号";
  String handelStr = "开始检测";
  String statuscode = "";
  String signimg = "";
  bool can_qianyue = false;
  initState() {
    super.initState();
    fluwx.weChatResponseEventHandler.listen((res) {
      print(res);
      if (res is fluwx.WeChatPaymentResponse) {
        if (res.isSuccessful) {
          //支付成功
          Toast.show('订单已支付，请等待系统处理', context);
        }
      }
    });
    formList = [
      {
        "title": '预约项目',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系人',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系电话',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约时间',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '品牌',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约车型',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车价',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      // {
      //   "title": '下单时间',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1)
      // },
    ];
    loadOrderInfo();
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    print(formList);
    Widget content;
    for (var item in formList) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Container(
              // color: Colors.white,
              height: 30,
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                        padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                        child: new Text(
                          item['title'],
                          style: TextStyle(
                              fontSize: 12,
                              color: Color.fromRGBO(51, 51, 51, 1)),
                        )),
                    flex: 1,
                  ),
                  new Padding(
                      padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                      child: new Text(
                        //'1212121',
                        item['sub_title'],
                        style: TextStyle(
                            fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
                      )),
                ],
              ))));
    }
    // return tiles;
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //设置订单开始
  setStart() {
    if (statuscode == "2") {
      //评价
      // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
      //   return new ComentOrderPage(this.oid);
      // }));
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        return new PapularinspectReults(this.oid, 1);
        //  return new StartJianPage(this.oid, handelStr, statuscode, 1);
      }));
    } else if (statuscode == "3") {
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        return new PapularinspectReults(this.oid, 1);
      }));
    }
    // Map<String, String> map = new Map();
    // map['id'] = this.oid;
    // //  SharedPreferences pref = await SharedPreferences.getInstance();
    // //  map["id"]=pref.getString('uid');
    // //  map["type"]="0";

    // HttpHelper.post(HttpHelper.API_UpdateOrderStart, (data) async {
    //   if (data != null) {
    //     print(data);
    //     if (data["code"].toString() == "1") {
    //       Navigator.of(context)
    //                       .push(new MaterialPageRoute(builder: (_) {
    //                     return new StartJianPage(this.oid,handelStr,statuscode,1);
    //                   }));
    //     }
    //   }
    // }, params: map);
  }

  //获取客户签约二维码
  getsigncode() async {
    Map<String, String> map = new Map();
    map['order_id'] = this.oid;
    //getgurantencode
    HttpHelper.post(HttpHelper.API_Guranteencode, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          setState(() {
            signimg = data['info']['imgurl'];
          });
        }
      }
    }, params: map);
  }

  //加载订单信息
  loadOrderInfo() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_OrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0)
              str = orderinfo["test_type"];
            else if (i == 1)
              str = orderinfo["name"];
            else if (i == 2)
              str = orderinfo["phone_num"];
            else if (i == 3)
              str = orderinfo["add_time"];
            else if (i == 4) {
              // str = orderinfo["brand_string"]["name"];
              str = "暂无";
              str = orderinfo["brand_string"]["name"];
            } else if (i == 5) {
              str = "暂无";
              str = orderinfo["cartype_string"]["name"];
            } else if (i == 6) {
              str = "暂无";
              str = orderinfo["carprice"] + '万';
            }
            // str = orderinfo["brand_string"]["name"];
            else if (i == 7) str = orderinfo["order_time"];

            item["sub_title"] = str;
          }
          String tempStr = "";
          String statu = data["info"]["status"];
          if (statu == "0") {
            tempStr = "待支付";
          } else if (statu == "1") {
            if(orderinfo['is_start'].toString()=="0"){
              tempStr = "检测师接单中，请耐心等待";
            }else{
            tempStr = "进行中";
            }
            handelStr = "继续检测";
          } else if (statu == "2") {
            tempStr = "已完成";
            handelStr = "查看结果";
            // getsigncode();
          } else {
            tempStr = "已完成";
            handelStr = "查看结果";
            // getsigncode();
          }

          if (data['info']['can_qianyue'] == true) {
            getsigncode();
          }
          setState(() {
            formList = oldlist;
            orderinfo = data["info"];
            price = data["info"]["orderPrice"];
            status = tempStr;
            order_sn = data["info"]["order_sn"];
            statuscode = statu;
            can_qianyue = data['info']['can_qianyue'];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //弹出付款方式
  poppaytype(orderid, rechcek) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 120,
            child: Column(
              children: [
                Container(
                  height: 40,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom:
                              BorderSide(width: 1, color: Colours.base_gray))),
                  child: Center(child: Text('付款方式')),
                ),
                InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      paybugroup(orderid);
                      // queryprolems(type, xsz_url, chejia.text, rechcek, 4);
                    },
                    child: Container(
                      height: 40,
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Colours.base_gray))),
                      child: Center(child: Text('套餐付费')),
                    )),
                InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      pay(orderid);
                      // queryprolems(type, xsz_url, chejia.text, rechcek, 3);
                    },
                    child: Container(
                      height: 40,
                      // decoration: BoxDecoration(
                      //   border: Border(bottom: BorderSide(
                      //     width: 1,color: Colours.base_gray
                      //   ))
                      // ),
                      child: Center(child: Text('微信支付')),
                    )),
              ],
            ),
          );
        });
  }

  //车商通过套餐下保修订单
  paybugroup(orderid) {
    Map<String, String> param = new Map();
    param['order_id'] = orderid;
    param['use_group'] = "1";
    HttpHelper.post(HttpHelper.API_pay, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["status"].toString() == "1") {
          var payinfo = data['result']['message'];
          Toast.show(payinfo, context);
          Navigator.pop(context);
        } else {
          var payinfo = data['result']['message'];
          Toast.show(payinfo, context);
        }
      }
    }, params: param);
  }

  pay(oid) {
    Map<String, String> param = new Map();
    param['order_id'] = oid;
    HttpHelper.post(HttpHelper.API_pay, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        if (data["status"].toString() == "1") {
          var payinfo = data['result']['pay_info'];
          print(payinfo['prepayid']['0']);
          fluwx.payWithWeChat(
              appId: Config.wx_appid,
              partnerId: payinfo['partnerid'],
              prepayId: payinfo['prepayid']['0'],
              packageValue: payinfo['package'],
              nonceStr: payinfo['noncestr'],
              timeStamp: int.parse(payinfo['timestamp']),
              sign: payinfo['sign']);
        } else {
          Toast.show(data['result']['message'], context);
          Navigator.pop(context);
        }
      }
    }, params: param);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          title: Text(
            '订单详情',
            style: TextStyle(color: Colors.white, fontSize: Config.title_size),
          ),
          backgroundColor: Colours.app_main,
          elevation: 0,
          iconTheme: new IconThemeData(color: Colors.white),
        ),
        body: Container(
          child: new ListView(
            children: <Widget>[
              Container(
                height: 150,
                color: Colours.app_main,
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(15, 50, 15, 10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          status,
                          style: TextStyle(fontSize: 18, color: Colors.white),
                        ),
                      ),
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          '订单编号：' + order_sn,
                          style: TextStyle(fontSize: 13, color: Colors.white),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              Container(
                height: 10,
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(13, 15, 15, 15),
                  child: Container(
                      // padding: new EdgeInsets.all(15),
                      height: 20,
                      // color: Color.fromRGBO(27, 182, 251, 1),
                      child: new Text(
                        '1',
                        style: TextStyle(
                            color: Color.fromRGBO(27, 182, 251, 1),
                            backgroundColor: Color.fromRGBO(27, 182, 251, 1)),
                      ))),
              Padding(
                  padding: new EdgeInsets.fromLTRB(15, 1, 15, 15),
                  child: buildcontent()),
              Padding(
                padding: new EdgeInsets.fromLTRB(0, 15, 25, 10),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '检测金额：¥' + price,
                    style: TextStyle(
                        fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
                  ),
                ),
              ),
              can_qianyue
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 20, 35, 10),
                      child: SizedBox(
                        width: 150,
                        height: 150,
                        child: Center(
                          child: signimg == ""
                              ? Text("")
                              : CachedNetworkImage(imageUrl: signimg),
                        ),
                      ),
                    )
                  : new Text(''),
              can_qianyue
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 0, 35, 0),
                      child: SizedBox(
                        width: double.infinity,
                        // height: 150,
                        child: Center(
                            child: Text(
                          "请客户使用微信扫码进入车魔估小程序进行签约确认！",
                          style: TextStyle(fontSize: 14, color: Colors.red),
                        )),
                      ),
                    )
                  : new Text(''),
              // statuscode == "2" || statuscode == "3"
              //     ? Padding(
              //         padding: new EdgeInsets.fromLTRB(35, 10, 35, 20),
              //         child: SizedBox(
              //             width: double.infinity,
              //             height: 50,
              //             child: new RaisedButton.icon(
              //               icon: new Image.asset(
              //                   'resource/images/user/answer.png'),
              //               label: Text(
              //                 handelStr,
              //                 style: TextStyle(fontSize: 15),
              //               ),
              //               // color: Color.fromRGBO(33, 192, 193, 1),
              //               color: Colours.app_main,
              //               textColor: Colors.white,
              //               onPressed: () {
              //                 setStart();
              //               },
              //             )),
              //       )
              //     : new Text(''),
              statuscode == "0"
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 20, 35, 20),
                      child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: new RaisedButton.icon(
                            icon: new Image.asset(
                                'resource/images/user/answer.png'),
                            label: Text(
                              '支付',
                              style: TextStyle(fontSize: 15),
                            ),
                            color: Colours.app_main,
                            textColor: Colors.white,
                            onPressed: () {
                              poppaytype(this.oid, 1);
                              //  pay(this.oid);
                            },
                          )),
                    )
                  : new Text('')
            ],
          ),
        ));
  }
}
